/*
 * @Author: hongbin
 * @Date: 2021-11-16 20:04:05
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-16 20:58:45
 * @Description:展示一条数据
 */
import { ArrowRight, DeleteForever, Edit } from "@mui/icons-material";
import { FC, useState } from "react";
import styled from "styled-components";

interface ItemProps {
  data: any;
  arrName?: string;
  main?: boolean; //最外层的item
  onDelete?: (_id: string) => void;
  onEdit?: (data: any) => void;
}

const DataItem: FC<ItemProps> = ({ data, arrName, main, onDelete, onEdit }) => {
  const [open, setOpen] = useState(false);
  const entries = Object.entries(data);

  return (
    <ItemStyled>
      <div>
        <ArrowRight
          onClick={() => setOpen(state => !state)}
          style={{ transform: `rotate(${open ? "90deg" : "0"})` }}
        />
        <span
          style={{
            display: "flex",
            alignItems: "center",
          }}
        >
          {arrName || data._id}
          {main ? (
            <FuncBtn
              onDelete={() => onDelete!(data._id)}
              onEdit={() => onEdit!(data)}
            />
          ) : null}
        </span>
        <span>
          {arrName ? `[${entries.length}]` : `${entries.length}个字段`}
        </span>
      </div>
      {open ? (
        <div>
          {entries.map((item: any, index: number) => {
            if (item.constructor === Object)
              return <DataItem data={item} key={index} />;

            const [key, value] = item;
            if (Array.isArray(value))
              return <DataItem data={value} arrName={key} key={key} />;

            const str = arrName ? item.toString() : value.toString();
            const fontSize = str.length > 30 ? 12 : "1rem";
            return (
              <div data-text key={key}>
                <span>{arrName ? index : key}</span>
                <span style={{ fontSize }}>{str}</span>
              </div>
            );
          })}
        </div>
      ) : null}
    </ItemStyled>
  );
};

export default DataItem;

interface FuncBtnProps {
  onDelete: () => void;
  onEdit: () => void;
}

const FuncBtn: FC<FuncBtnProps> = ({ onDelete, onEdit }) => (
  <div data-func-btn>
    <DeleteForever onClick={onDelete} />
    <Edit onClick={onEdit} />
  </div>
);

const ItemStyled = styled.div`
  & > div:first-child {
    display: flex;
    align-items: center;
    span {
      flex: 1;
      [data-func-btn] {
        transition: opacity var(--transition-duration) linear;
        opacity: 0;
        svg {
          cursor: pointer;
        }
      }
    }
    :hover {
      [data-func-btn] {
        opacity: 1;
      }
    }
  }
  & > div:nth-child(2) {
    margin-left: 3rem;

    [data-text] {
      display: flex;
      span {
        padding: 0.2rem 0;
        width: 50%;
      }
    }
  }
`;
